{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Solution Notebook"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Problem: Find an element in a sorted array that has been rotated a number of times.\n",
    "\n",
    "* [Constraints](#Constraints)\n",
    "* [Test Cases](#Test-Cases)\n",
    "* [Algorithm](#Algorithm)\n",
    "* [Code](#Code)\n",
    "* [Unit Test](#Unit-Test)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Constraints\n",
    "\n",
    "* Is the input an array of ints?\n",
    "    * Yes\n",
    "* Can the input have duplicates?\n",
    "    * Yes\n",
    "* Do we know how many times the array was rotated?\n",
    "    * No\n",
    "* Was the array originally sorted in increasing or decreasing order?\n",
    "    * Increasing\n",
    "* For the output, do we return the index?\n",
    "    * Yes\n",
    "* Can we assume the inputs are valid?\n",
    "    * No\n",
    "* Can we assume this fits memory?\n",
    "    * Yes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Test Cases\n",
    "\n",
    "* None -> Exception\n",
    "* [] -> None\n",
    "* Not found -> None\n",
    "* General case with duplicates\n",
    "* General case without duplicates"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Algorithm\n",
    "\n",
    "### General case without dupes\n",
    "\n",
    "<pre>\n",
    "\n",
    "index                   0   1   2   3   4   5   6   7   8   9\n",
    "input                 [ 1,  3,  5,  6,  7,  8,  9, 10, 12, 14]\n",
    "input rotated 1x      [10, 12, 14,  1,  3,  5,  6,  7,  8,  9]\n",
    "input rotated 2x      [ 5,  6,  7,  8,  9, 10, 12, 14,  1,  3]\n",
    "input rotated 3x      [10, 12, 14,  1,  3,  5,  6,  7,  8,  9]\n",
    "\n",
    "find 1\n",
    "len = 10\n",
    "mid = 10 // 2 = 5\n",
    "                        s                   m               e\n",
    "index                   0   1   2   3   4   5   6   7   8   9\n",
    "input                 [10, 12, 14,  1,  3,  5,  6,  7,  8,  9]\n",
    "\n",
    "input[start] > input[mid]: Left half is rotated\n",
    "input[end] >= input[mid]: Right half is sorted\n",
    "1 is not within input[mid+1] to input[end] on the right side, go left\n",
    "\n",
    "                        s       m       e\n",
    "index                   0   1   2   3   4   5   6   7   8   9\n",
    "input                 [10, 12, 14,  1,  3,  5,  6,  7,  8,  9]\n",
    "\n",
    "input[start] <= input[mid]: Right half is rotated\n",
    "input[end] >= input[mid]: Left half is sorted\n",
    "1 is not within input[left] to input[mid-1] on the left side, go right\n",
    "\n",
    "</pre>\n",
    "\n",
    "### General case with dupes\n",
    "\n",
    "<pre>\n",
    "\n",
    "                        s                   m               e\n",
    "index                   0   1   2   3   4   5   6   7   8   9\n",
    "input                 [ 1,  1,  1,  1,  1,  1,  1,  1,  1,  2]\n",
    "\n",
    "input[start] == input[mid], input[mid] != input[end], go right\n",
    "\n",
    "input rotated 1x      [ 1,  1,  2,  1,  1,  1,  1,  1,  1,  1]\n",
    "\n",
    "input[start] == input[mid] == input[end], search both sides\n",
    "\n",
    "</pre>\n",
    "\n",
    "Complexity:\n",
    "* Time: O(log n) if there are no duplicates, else O(n)\n",
    "* Space: O(m), where m is the recursion depth"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Array(object):\n",
    "\n",
    "    def search_sorted_array(self, array, val):\n",
    "        if array is None or val is None:\n",
    "            raise TypeError('array or val cannot be None')\n",
    "        if not array:\n",
    "            return None\n",
    "        return self._search_sorted_array(array, val, start=0, end=len(array) - 1)\n",
    "\n",
    "    def _search_sorted_array(self, array, val, start, end):\n",
    "        if end < start:\n",
    "            return None\n",
    "        mid = (start + end) // 2\n",
    "        if array[mid] == val:\n",
    "            return mid\n",
    "        # Left side is sorted\n",
    "        if array[start] < array[mid]:\n",
    "            if array[start] <= val < array[mid]:\n",
    "                return self._search_sorted_array(array, val, start, mid - 1)\n",
    "            else:\n",
    "                return self._search_sorted_array(array, val, mid + 1, end)\n",
    "        # Right side is sorted\n",
    "        elif array[start] > array[mid]:\n",
    "            if array[mid] < val <= array[end]:\n",
    "                return self._search_sorted_array(array, val, mid + 1, end)\n",
    "            else:\n",
    "                return self._search_sorted_array(array, val, start, mid - 1)\n",
    "        # Duplicates\n",
    "        else:\n",
    "            if array[mid] != array[end]:\n",
    "                return self._search_sorted_array(array, val, mid + 1, end)\n",
    "            else:\n",
    "                result = self._search_sorted_array(array, val, start, mid - 1)\n",
    "                if result != None:\n",
    "                    return result\n",
    "                else:\n",
    "                    return self._search_sorted_array(array, val, mid + 1, end)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Unit Test"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overwriting test_search_sorted_array.py\n"
     ]
    }
   ],
   "source": [
    "%%writefile test_search_sorted_array.py\n",
    "import unittest\n",
    "\n",
    "\n",
    "class TestArray(unittest.TestCase):\n",
    "\n",
    "    def test_search_sorted_array(self):\n",
    "        array = Array()\n",
    "        self.assertRaises(TypeError, array.search_sorted_array, None)\n",
    "        self.assertEqual(array.search_sorted_array([3, 1, 2], 0), None)\n",
    "        self.assertEqual(array.search_sorted_array([3, 1, 2], 0), None)\n",
    "        data = [10, 12, 14,  1,  3,  5,  6,  7,  8,  9]\n",
    "        self.assertEqual(array.search_sorted_array(data, val=1), 3)\n",
    "        data = [ 1,  1,  2,  1,  1,  1,  1,  1,  1,  1]\n",
    "        self.assertEqual(array.search_sorted_array(data, val=2), 2)\n",
    "        print('Success: test_search_sorted_array')\n",
    "\n",
    "\n",
    "def main():\n",
    "    test = TestArray()\n",
    "    test.test_search_sorted_array()\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Success: test_search_sorted_array\n"
     ]
    }
   ],
   "source": [
    "%run -i test_search_sorted_array.py"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
